package com.liu.xxxlu_robot;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.liu.xxxlu_robot.tool.Info;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private ListView mLvlist;
    private List<ChatInfo> mChatInfos;
    private Button mSend;
    private EditText mMsg;
    private LvlistAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLvlist = (ListView) findViewById(R.id.lv_listview);

        sendInfo();

        mChatInfos = new ArrayList<ChatInfo>();
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setDate(new Date(System.currentTimeMillis()));
        chatInfo.setImg(false);
        chatInfo.setMsg(getString(R.string.robot));
        chatInfo.setIsput(false);
        mChatInfos.add(chatInfo);

        mAdapter = new LvlistAdapter();
        mLvlist.setAdapter(mAdapter);
    }

    /**
     * 发送事件
     */
    private void sendInfo() {
        mSend = (Button) findViewById(R.id.btn_send);
        mMsg = (EditText) findViewById(R.id.et_edit);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send();
            }
        });
        mMsg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {

                if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    // do something
                    send();
                    return true;
                }
                return false;
            }
        });
    }

    private void send() {
        if (!TextUtils.isEmpty(mMsg.getText())) {
            ChatInfo chatInfo = new ChatInfo();
            chatInfo.setIsput(true);
            String msg = String.valueOf(mMsg.getText());
            chatInfo.setMsg(msg);
            mChatInfos.add(chatInfo);
            mAdapter.notifyDataSetChanged();
            mMsg.setText("");
            String encode = null;
            //对用户输入的空格进行格式化处理
            try {
                encode = URLEncoder.encode(msg,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String url = Info.API_URL + "?key=" + Info.API_KEY + "&info=" + encode + "&userid=" + Info.DB_API;
            new RequestData().execute(url);
            Log.i(TAG, "点击发送处理结束，拼接地址：" + url);
        } else {
            Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
        }
    }

    private class LvlistAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return mChatInfos.size();
        }

        @Override
        public ChatInfo getItem(int i) {
            return mChatInfos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            InitView initView = new InitView();
            if (view == null) {
                view = View.inflate(MainActivity.this, R.layout.list_item, null);
                initView.mRl_robot = (RelativeLayout) view.findViewById(R.id.rl_robot);
                initView.mRl_me = (RelativeLayout) view.findViewById(R.id.rl_me);
                initView.headimg = (ImageView) view.findViewById(R.id.iv_headimg_me);
                initView.robottext = (TextView) view.findViewById(R.id.tv_text_robot);
                initView.metext = (TextView) view.findViewById(R.id.tv_text_me);
                view.setTag(initView);
            } else {
                initView = (InitView) view.getTag();
            }
            if (mChatInfos.get(i).isput()) {
                //是用户输入的信息
                initView.mRl_robot.setVisibility(View.GONE);
                initView.mRl_me.setVisibility(View.VISIBLE);
                initView.metext.setText(mChatInfos.get(i).getMsg());
            } else {
                //是机器人的信息
                initView.mRl_robot.setVisibility(View.VISIBLE);
                initView.mRl_me.setVisibility(View.GONE);
                initView.robottext.setText(mChatInfos.get(i).getMsg());
            }
            return view;
        }
    }

    static class InitView {
        public ImageView headimg;//用户头像
        public TextView robottext;//机器人的话
        public TextView metext;//用户的话
        public RelativeLayout mRl_robot;//机器人布局
        public RelativeLayout mRl_me;//用户布局
    }

    /**
     * 网络数据请求和UI更新
     */
    class RequestData extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {

            try {
                Log.i(TAG, "开始网络请求");
                URL url = new URL(strings[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(30000);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("apikey", Info.DB_API);
                connection.connect();

                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream, "UTF-8");

                char[] buffer = new char[1024];
                reader.read(buffer);
                String content = new String(buffer);
                Log.i(TAG, "请求结束，数据为" + content);

                return content;
            } catch (java.io.IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //解析数据
            String text = null;
            try {
                JSONObject jsonObject = new JSONObject(s);
                text = jsonObject.getString("text");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ChatInfo chatInfo = new ChatInfo();
            chatInfo.setMsg(text);
            chatInfo.setIsput(false);
            mChatInfos.add(chatInfo);
            mAdapter.notifyDataSetChanged();
        }
    }
}
